
package com.jf.cloud.multishop.controller.app;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.constant.OrderCacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.multishop.bo.mongo.MongoShopWalletLogBO;
import com.jf.cloud.multishop.constant.ShopWalletAmountType;
import com.jf.cloud.multishop.constant.ShopWalletChangeReason;
import com.jf.cloud.multishop.constant.ShopWalletIoType;
import com.jf.cloud.multishop.service.ShopCollectionService;
import com.jf.cloud.multishop.service.ShopWalletLogService;
import com.jf.cloud.multishop.service.ShopWalletService;
import com.jf.cloud.multishop.vo.ShopCollectionVO;
import com.jf.cloud.multishop.vo.ShopWalletVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户店铺收藏记录
 *
 * @author zz
 * @date 2021-02-23 14:41:42
 */
@RestController("appUserCollectionShopController")
@RequestMapping("/user_collection_shop")
@Tag(name = "app-用户店铺收藏记录")
public class ShopCollectionController {

    @Autowired
    private ShopCollectionService shopCollectionService;
    @Autowired
    private ShopWalletService shopWalletService;

    @Autowired
    private ShopWalletLogService shopWalletLogService;

    @GetMapping("/page")
    @Operation(summary = "分页返回收藏数据", description = "根据用户id获取")
    public ServerResponseEntity<PageVO<ShopCollectionVO>> getUserCollectionDtoPageByUserId(@Valid PageDTO pageDTO, @ParameterObject String shopName) {
        Long userId = AuthUserContext.get().getUserId();
        PageVO<ShopCollectionVO> shopCollectionPage = shopCollectionService.getUserCollectionShopPageByUserIdAndShopName(pageDTO, userId, shopName);
        return ServerResponseEntity.success(shopCollectionPage);
    }

    @GetMapping("/ma/is_collection")
    @Operation(summary = "根据店铺id获取该店铺是否在收藏夹中", description = "传入收藏店铺id")
    public ServerResponseEntity<Boolean> isCollection(@ParameterObject Long shopId) {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        // 没有登陆就返回false (未收藏店铺)
        if (null == userInfoInTokenBO) {
            return ServerResponseEntity.success(Boolean.FALSE);
        }
        return ServerResponseEntity.success(0 < shopCollectionService.countByShopIdAndUserId(shopId, userInfoInTokenBO.getUserId()));
    }

    @PostMapping("/add_or_cancel")
    @Operation(summary = "添加/取消收藏", description = "传入收藏店铺id,如果店铺未收藏则收藏店铺，已收藏则取消收藏")
    @Parameter(name = "shopId", description = "店铺id", required = true)
    public ServerResponseEntity<Boolean> addOrCancel(@RequestBody Long shopId) {
        Long userId = AuthUserContext.get().getUserId();
        Boolean isAdd = shopCollectionService.addOrCancel(shopId, userId);
        return ServerResponseEntity.success(isAdd);
    }

    @PostMapping("/batch_cancel")
    @Operation(summary = "批量取消收藏", description = "传入收藏店铺id")
    @Parameter(name = "shopIds", description = "店铺Id", required = true)
    public ServerResponseEntity<Boolean> batchCancel(@RequestBody List<Long> shopIds) {
        Long userId = AuthUserContext.get().getUserId();
        if (CollectionUtils.isEmpty(shopIds)) {
            return ServerResponseEntity.success(false);
        }
        return ServerResponseEntity.success(shopCollectionService.batchCancel(shopIds, userId));
    }

    /**
     * 查询用户收藏店铺数量
     */
    @GetMapping("count")
    @Operation(summary = "查询用户收藏店铺数量", description = "查询用户收藏店铺数量")
    public int findUserCollectionCount() {
        Long userId = AuthUserContext.get().getUserId();
        return shopCollectionService.countByShopIdAndUserId(null, userId);
    }

    @PostMapping("/qrcode_recharge_shop")
    @Operation(summary = "充值订单", description = "生成余额充值订单，保存充值记录")
    public ServerResponseEntity<Long> qrcode_recharge(@Valid @RequestParam BigDecimal rechargeAmount, @Valid @RequestParam Long shopId) {
        Long amount = PriceUtil.toLongCent(rechargeAmount);
        if (amount < 1) {
            throw new LuckException("充值金额有误");
        }
        ShopWalletVO shopWallet = shopWalletService.getByShopId(shopId);
        long userBalance = shopWallet.getSettledAmount() + amount;

        if (userBalance > Constant.MAX_USER_BALANCE) {
            throw new LuckException("此次充值会导致余额超出最大限制，故无法进行此操作,请减少充值金额后重试");
        }
        // 防止重复提交修改商家余额
//        boolean cad = RedisUtil.cad(OrderCacheNames.RECHARGE_MULTISHOP_KEY + CacheNames.UNION + userId+ CacheNames.UNION + shopId, String.valueOf(amount));
//        if (!cad) {
//            return ServerResponseEntity.fail(ResponseEnum.REPEAT_ORDER);
//        }
        Long userId = AuthUserContext.get().getUserId();
        MongoShopWalletLogBO shopWalletLog = new MongoShopWalletLogBO();
        shopWalletLog.setShopId(shopId);
        BigDecimal rate = new BigDecimal("0.944");
        Long shopChangeAmount = PriceUtil.toLongCent(rechargeAmount.multiply(rate));
        shopWalletLog.setShopChangeAmount(shopChangeAmount);
        shopWalletLog.setUserAmount(amount);
        shopWalletLog.setOrderId(userId);
        shopWalletLog.setShopIoType(ShopWalletIoType.INCOME.value());
        shopWalletLog.setReason(ShopWalletChangeReason.SUCCESS_QRCODE_RECHARGE.value());
        shopWalletLog.setAmountType(ShopWalletAmountType.SETTLED_AMOUNT.value());
        shopWalletLog.setCreateTime(new Date());
        shopWalletLog.setPlatformCommission(amount - shopChangeAmount);
        shopWalletLog.setShopPlatformCommission(amount - shopChangeAmount);
        shopWalletLog.setPlatformIoType(1);
        shopWalletLog.setPlatformChangeAmount(amount - shopChangeAmount);
        shopWalletLogService.saveMongo(shopWalletLog);
//        RedisUtil.STRING_REDIS_TEMPLATE.opsForValue().set(OrderCacheNames.RECHARGE_MULTISHOP_KEY + CacheNames.UNION + userId+ CacheNames.UNION + shopId, String.valueOf(amount),10, TimeUnit.SECONDS);
        return ServerResponseEntity.success(shopWalletLog.getWalletLogId());
    }

    @PostMapping("/qrcode_recharge_shop_test")
    @Operation(summary = "充值订单", description = "生成余额充值订单，保存充值记录")
    public ServerResponseEntity<Long> qrcode_recharge_shop_test(@Valid @RequestParam BigDecimal rechargeAmount, @Valid @RequestParam Long shopId) {
        Long amount = PriceUtil.toLongCent(rechargeAmount);
        if (amount < 1) {
            throw new LuckException("充值金额有误");
        }
        ShopWalletVO shopWallet = shopWalletService.getByShopId(shopId);
        long userBalance = shopWallet.getSettledAmount() + amount;

        if (userBalance > Constant.MAX_USER_BALANCE) {
            throw new LuckException("此次充值会导致余额超出最大限制，故无法进行此操作,请减少充值金额后重试");
        }
        Long userId = AuthUserContext.get().getUserId();
//        // 防止重复提交修改商家余额
        Long cad = RedisUtil.getLongValue(OrderCacheNames.RECHARGE_MULTISHOP_KEY + CacheNames.UNION + userId + CacheNames.UNION + shopId);
        if (null != cad) {
            return ServerResponseEntity.fail(ResponseEnum.REPEAT_ORDER);
        }
        RedisUtil.STRING_REDIS_TEMPLATE.opsForValue().set(OrderCacheNames.RECHARGE_MULTISHOP_KEY + CacheNames.UNION + userId + CacheNames.UNION + shopId, String.valueOf(amount), 10, TimeUnit.SECONDS);
        MongoShopWalletLogBO shopWalletLog = new MongoShopWalletLogBO();
        shopWalletLog.setShopId(shopId);
        BigDecimal rate = new BigDecimal("0.944");
        Long shopChangeAmount = PriceUtil.toLongCent(rechargeAmount.multiply(rate));
        shopWalletLog.setShopChangeAmount(shopChangeAmount);
        shopWalletLog.setUserAmount(amount);
        shopWalletLog.setOrderId(userId);
        shopWalletLog.setShopIoType(ShopWalletIoType.INCOME.value());
        shopWalletLog.setReason(ShopWalletChangeReason.SUCCESS_QRCODE_RECHARGE.value());
        shopWalletLog.setAmountType(ShopWalletAmountType.SETTLED_AMOUNT.value());
        shopWalletLog.setCreateTime(new Date());
        shopWalletLog.setPlatformCommission(amount - shopChangeAmount);
        shopWalletLog.setShopPlatformCommission(amount - shopChangeAmount);
        shopWalletLog.setPlatformIoType(1);
        shopWalletLog.setPlatformChangeAmount(amount - shopChangeAmount);
//        shopWalletLogService.saveMongo(shopWalletLog);
        return ServerResponseEntity.success(shopWalletLog.getWalletLogId());
    }
}